import { SOCKET_HTTP_URL } from "@/constant";
import {
  closeWebSocket as closeAllWebSocket,
  creatWebSocket
} from "@/utils/http/webSocket";
import { message } from "@/utils/message";
import { usePageVariablesStoreHook } from "@/store/modules/pageVariables";
import { useUserStoreHook } from "@/store/modules/user";
import { addDialog, closeDialog } from "@/components/ReDialog";
import messages from "../layoutscrreen/head/message.vue";
import messagehead from "../layoutscrreen/head/messagehead.vue";
import { useDataDashboardThemeStoreHook } from "@/store/modules/data-dashboard-theme";
import { storageLocal } from "@pureadmin/utils";
import { getToken, userKey } from "@/utils/auth";
import { emitter } from '@/utils/mitt'
import { getAlarmRecord } from "@/api/screen";


const usePageVariablesStore = ref(usePageVariablesStoreHook());
const useDataDashboardThemeStore = ref(useDataDashboardThemeStoreHook());
const isShowPopup = ref(false);
const websocket = ref(null);
const socketType = ref(null);

let socketState = "wss";
let rec = null;
let token = getToken().accessToken.split(' ')[1];
let timer = null
const connectWebSocket = (type = 2) => {
  // setInterval(() => {
  //   messageShow(true)
  // }, 1000)
  /** 1单位2项目 */
  socketType.value = type;
  let wsUrl = null;
  if (type == 1) {
    wsUrl = `${socketState}://${SOCKET_HTTP_URL}/system/ws/${storageLocal().getItem(userKey).userInfo?.id}_${new Date().getTime()}/screen_unity_${usePageVariablesStore.value.getScreen()?.unit?.id}/${token}`;
  } else if (type == 2) {
    wsUrl = `${socketState}://${SOCKET_HTTP_URL}/system/ws/${storageLocal().getItem(userKey).userInfo?.id}_${new Date().getTime()}/screen_${usePageVariablesStore.value.getScreen()?.project?.id}/${token}`;
  }
  if (websocket.value) {
    closeWebSocket();
  }
  websocket.value = creatWebSocket(
    wsUrl,
    websocketonmessage,
    websocketonerror,
    websocketclose
  );
  timer = setInterval(() => {
    websocket.value && messageSen()
  }, 5000)
};
const websocketonmessage = (e) => {
  let res = JSON.parse(e.data)
  /** 告警事件更新 */
  emitter.emit('alarmEvents', res);
  if (socketType.value == 1) {
    /** 单位告警事件更新 */
    emitter.emit('alarmEventsUnit', res)
  } else if (socketType.value == 2) {
    /** 项目告警事件更新 */
    emitter.emit('alarmEventsProject', res)
    if (res?.message?.drawingId != 0 || res?.message?.buildingId != 0) {
      /** 建筑图纸告警事件更新 */
      emitter.emit('alarmEventsBuilding', res)
    }
  }
  if (res.message.hasAlarm) {
    messageShow(true);
  }
};

const messageSen = () => {
  emitter.emit('alarmEvents');
  emitter.emit('alarmEventsUnit')
  emitter.emit('alarmEventsProject')
  emitter.emit('alarmEventsBuilding')
}

const websocketonerror = e => {
  // console.log("连接错误，尝试重新连接");
  rec && clearTimeout(rec);
  timer && clearInterval(timer)
  rec = setTimeout(() => {
    // 延迟5秒重连  避免过多次过频繁请求重连
    // if (socketState == "wss") {
    //   socketState = "ws";
    // } else {
    socketState = "wss";
    // }
    // console.log("重连");

    connectWebSocket();
  }, 3000);
};
const websocketclose = e => {
  timer && clearInterval(timer)
  // console.log("close", e);
  // message('websocket连接关闭', {
  //     type: 'warning'
  // })
};
const closeWebSocket = () => {
  rec && clearTimeout(rec);
  timer && clearInterval(timer)
  closeAllWebSocket();
};
//消息弹出框
const messageShow = (isAuto = false) => {
  getAlarmRecord().then(res => {
    if (res.result.total == 0) {
      if (!isAuto) {
        message('没有新的告警信息', {
          type: 'warning'
        })
      }
    } else {
      if (
        !isShowPopup.value &&
        (!isAuto ||
          (isAuto && !useDataDashboardThemeStore.value.getCloseAutoPopUp()))
      ) {
        if (isAuto) {
          useDataDashboardThemeStore.value.openSound = true
          let audioElement = document.createElement("audio");
          audioElement.src = '/src/assets/mp3/alarmAudio.mp3'
          audioElement.play();
          audioElement.addEventListener('ended', () => {
            audioElement.play();
          })
          let watchOpenSound = watch(() => useDataDashboardThemeStore.value.openSound, () => {
            if (!useDataDashboardThemeStore.value.openSound) {
              audioElement.pause()
              audioElement.remove()
              watchOpenSound()
            }
          })
        }
        let headRef = ref()
        let contentRef = ref()
        isShowPopup.value = true;
        addDialog({
          headerRenderer: () => h(messagehead, {
            ref: headRef,
            onReAlarmList: () => {
              contentRef.value.reList()
            }
          }),
          hideFooter: true,
          width: "1600px",
          draggable: true,
          closeOnClickModal: false,
          contentRenderer: () => h(messages, { ref: contentRef }),
          props: {},
          openAutoFocus({ options, index }) {
            options.props.closePopup = () => {
              closeDialog(options, index)
              isShowPopup.value = false;
              useDataDashboardThemeStore.value.openSound = false
            }
            options.props.closeSound = () => {
              headRef.value.closeSound()
            }
          },
          close({ options, index }) {
            isShowPopup.value = false;
            headRef.value.closeSound()
            useDataDashboardThemeStore.value.openSound = false
          }
        });
      }
    }
  })
};

export { connectWebSocket, closeWebSocket, messageShow };
